import { acceptHMRUpdate, defineStore } from "pinia";
import { computed, shallowRef } from "vue";
import { existsFile, readDir } from "@/framework/util/fs";
import path from "path-browserify-esm";
import type { GenericToolItemVO } from "@/pages/tools/common/vos";
import { array2object } from "@/framework/util/collections";
import { useLocalRef } from "@/framework/vue/hooks";
import semver from "semver";

const defaultInstallDir = "C:/Dev/Denv/mvnd";

export const useMvndStore = defineStore("java-mvnd", () => {
  const installPath = useLocalRef("java.mvnd.install.path", defaultInstallDir);
  const setInstallPath = (path: string) => (installPath.value = path);

  const versionList = shallowRef<GenericToolItemVO[]>([]);
  const versionMap = computed(() => array2object(versionList.value, "version"));

  async function scanInstalledMvnd() {
    try {
      const list: GenericToolItemVO[] = [];
      const items = await readDir(installPath.value);
      for (const it of items) {
        if (it.startsWith("maven-mvnd-")) {
          const dir = path.join(installPath.value, it);
          const mavenBinFile = path.join(dir, __WINDOWS__ ? "bin/mvnd.exe" : "bin/mvnd");
          if (await existsFile(mavenBinFile)) {
            const [, , ...omit] = it.split("-");
            list.push({ version: omit.join("-"), installPath: dir, bin: mavenBinFile });
          }
        }
      }

      list.sort((a, b) => semver.compare(b.version, a.version));
      versionList.value = list;
    } catch (e: any) {
      console.error("scanInstalledMaven error", e);
      versionList.value = [];
    }
  }

  return {
    installPath: installPath,
    setInstallPath: setInstallPath,

    versionList: versionList,
    versionMap: versionMap,
    scanInstalledMvnd: scanInstalledMvnd,
  };
});

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useMvndStore, import.meta.hot));
}
